﻿using System;
using System.Collections.Generic;

namespace Flagwind.Externals.Redis.Commands
{
	[Flagwind.Services.CommandOption("interval", Type = typeof(int), DefaultValue = 1)]
	public class DictionaryDecrementCommand : RedisCommandBase
	{
		#region 构造方法

		public DictionaryDecrementCommand() : base("Decrement")
		{
		}

		public DictionaryDecrementCommand(IRedisService redis) : base(redis, "Decrement")
		{
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(Services.CommandContext context)
		{
			if(context.Expression.Arguments.Length < 2)
				throw new Flagwind.Services.CommandException("The arguments is not enough.");

			if(context.Expression.Arguments.Length % 2 != 0)
				throw new Flagwind.Services.CommandException("The count arguments must be an even number.");

			var interval = context.Expression.Options.GetValue<int>("interval");
			var result = new List<long>(context.Expression.Arguments.Length / 2);

			for(int i = 0; i < context.Expression.Arguments.Length / 2; i++)
			{
				var dictionary = this.Redis.GetDictionary(context.Expression.Arguments[i * 2]);

				if(dictionary == null)
				{
					context.Error.WriteLine($"The '{context.Expression.Arguments[i * 2]}' dictionary is not existed.");
					return 0;
				}

				result.Add(dictionary.Decrement(context.Expression.Arguments[i * 2 + 1], interval));
				context.Output.WriteLine(result.ToString());
			}

			if(result.Count == 1)
				return result[0];
			else
				return result;
		}

		#endregion
	}
}